import 'package:baby_health_tracker/widgets/neumorphic_listtile.dart';
import 'package:flutter/material.dart';
import '../model/baby.dart';
import '../service/database_service.dart';
import '../service/settings_service.dart';
import '../service/theme_notifier.dart';
import '../service/theme_service.dart';
import '../widgets/edit_baby_dialog.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';


class SettingsTab extends StatefulWidget {
  @override
  _SettingsTabState createState() => _SettingsTabState();
}

class _SettingsTabState extends State<SettingsTab> {
  List<Baby> _babies = [];
  bool _isDarkMode = false;
  bool _notificationsEnabled = true;
  bool _backupReminderEnabled = false;
  String _language = 'zh_CN';

  @override
  void initState() {
    super.initState();
    _loadInitialData();
  }

  Future<void> _loadInitialData() async {
    await Future.wait([_loadSettings(), _loadBabies()]);
  }

  Future<void> _loadSettings() async {
    final settings = await SettingsService.getInstance();
    setState(() {
      _isDarkMode = settings.isDarkMode;
      _notificationsEnabled = settings.notificationsEnabled;
      _backupReminderEnabled = settings.backupReminderEnabled;
      _language = settings.language;
    });
  }

  Future<void> _loadBabies() async {
    final babies = await DatabaseService().getAllBabies();
    setState(() {
      _babies = babies;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('设置'), automaticallyImplyLeading: false),
      body: ListView(
        children: [
          _buildBabyProfiles(),
          Divider(),
          _buildAppSettings(),
          Divider(),
          _buildDataManagement(),
          Divider(),
          _buildAbout(),
        ],
      ),
    );
  }

  Widget _buildBabyProfiles() {
    return ListenableBuilder(
      listenable: ThemeNotifier.instance,
      builder: (context, _) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '宝宝档案',
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
            ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: _babies.length,
              itemBuilder: (context, index) {
                final baby = _babies[index];
                return ListTile(
                  leading:
                      baby.avatarUrl != null
                          ? CircleAvatar(
                            backgroundImage: FileImage(File(baby.avatarUrl!)),
                          )
                          : CircleAvatar(child: Text(baby.name[0])),
                  title: Text(baby.name),
                  subtitle: Text(
                    '${baby.gender == 'M' ? '男' : '女'} · ${baby.birthDate.year}年${baby.birthDate.month}月${baby.birthDate.day}日',
                  ),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (baby.isDefault)
                        Padding(
                          padding: EdgeInsets.only(right: 8),
                          child: Chip(
                            label: Text('默认'),
                            backgroundColor: Theme.of(
                              context,
                            ).colorScheme.primary.withOpacity(0.1),
                            labelStyle: TextStyle(
                              color: Theme.of(context).colorScheme.primary,
                            ),
                          ),
                        ),
                      IconButton(
                        icon: Icon(Icons.edit),
                        onPressed: () => _editBaby(baby),
                      ),
                    ],
                  ),
                  // onLongPress: () => _showBabyOptions(baby),
                );
              },
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: ElevatedButton.icon(
                icon: Icon(Icons.add),
                label: Text('添加宝宝'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  foregroundColor: Theme.of(context).colorScheme.onPrimary,
                ),
                onPressed: _addBaby,
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildAppSettings() {
    return ListenableBuilder(
      listenable: ThemeNotifier.instance,
      builder: (context, _) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '应用设置',
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
            ListTile(
              leading: const Icon(Icons.color_lens),
              title: const Text('主题颜色'),
              subtitle: Text(ThemeNotifier.instance.currentTheme),
              onTap: _showThemeSelector, trailing: SizedBox(),
            ),
            SwitchListTile(
              title: Text('通知提醒'),
              subtitle: Text('接收喂奶、服药等提醒'),
              value: _notificationsEnabled,
              onChanged: _toggleNotifications,
            ),
            SwitchListTile(
              title: Text('备份提醒'),
              subtitle: Text('定期提醒备份数据'),
              value: _backupReminderEnabled,
              onChanged: _toggleBackupReminder,
            ),
            ListTile(
              title: Text('重置设置'),
              subtitle: Text('恢复默认设置'),
              trailing: Icon(
                Icons.restore,
                color: Theme.of(context).colorScheme.primary,
              ),
              onTap: _resetSettings, leading: SizedBox(),
            ),
          ],
        );
      },
    );
  }

  Widget _buildDataManagement() {
    return ListenableBuilder(
      listenable: ThemeNotifier.instance,
      builder: (context, _) {
        final iconColor = Theme.of(context).colorScheme.primary;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '数据管理',
                style: Theme.of(context).textTheme.titleLarge,
              ),
            ),
            ListTile(
              leading: Icon(Icons.backup, color: iconColor),
              title: Text('备份数据'),
              subtitle: Text('导出所有数据到文件'),
              onTap: _backupData, trailing: SizedBox(),
            ),
            ListTile(
              leading: Icon(Icons.restore, color: iconColor),
              title: Text('恢复数据'),
              subtitle: Text('从备份文件恢复'),
              onTap: _restoreData, trailing: SizedBox(),
            ),
            ListTile(
              leading: Icon(Icons.delete_forever, color: Colors.red),
              title: Text('清除数据'),
              subtitle: Text('删除所有记录'),
              onTap: _clearData, trailing: SizedBox(),
            ),
          ],
        );
      },
    );
  }

  Widget _buildAbout() {
    return ListenableBuilder(
      listenable: ThemeNotifier.instance,
      builder: (context, _) {
        final iconColor = Theme.of(context).colorScheme.primary;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text('关于', style: Theme.of(context).textTheme.titleLarge),
            ),
            ListTile(
              leading: Icon(Icons.info, color: iconColor),
              title: Text('版本信息'),
              subtitle: Text('v1.0.0'), trailing: SizedBox(),
            ),
            ListTile(
              leading: Icon(Icons.privacy_tip, color: iconColor),
              title: Text('隐私政策'),
              onTap: _showPrivacyPolicy, subtitle: SizedBox(), trailing: SizedBox(),
            ),
          ],
        );
      },
    );
  }

  Future<void> _addBaby() async {
    final result = await showDialog<Baby>(
      context: context,
      builder: (context) => EditBabyDialog(),
    );

    if (result != null) {
      await DatabaseService().addBaby(result);
      _loadBabies();
    }
  }

  Future<void> _editBaby(Baby baby) async {
    final result = await showDialog<Baby>(
      context: context,
      builder: (context) => EditBabyDialog(baby: baby),
    );

    if (result != null) {
      await DatabaseService().updateBaby(result);
      _loadBabies();
    }
  }

  Future<void> _showBabyOptions(Baby baby) async {
    final theme = Theme.of(context);
    showModalBottomSheet(
      context: context,
      builder:
          (context) => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (!baby.isDefault)
                ListTile(
                  leading: Icon(
                    Icons.check_circle,
                    color: theme.colorScheme.primary,
                  ),
                  title: Text('设为默认'),
                  onTap: () async {
                    await DatabaseService().setDefaultBaby(baby.id);
                    Navigator.pop(context);
                    _loadBabies();
                  },
                ),
              ListTile(
                leading: Icon(Icons.delete, color: Colors.red),
                title: Text('删除', style: TextStyle(color: Colors.red)),
                onTap: () => _deleteBaby(baby),
              ),
            ],
          ),
    );
  }

  Future<void> _deleteBaby(Baby baby) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text('删除确认'),
            content: Text('确定要删除${baby.name}的所有数据吗？此操作不可恢复。'),
            actions: [
              TextButton(
                child: Text('取消'),
                onPressed: () => Navigator.pop(context, false),
              ),
              TextButton(
                child: Text('删除'),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          ),
    );

    if (confirmed == true) {
      await DatabaseService().deleteBaby(baby.id);
      _loadBabies();
    }
  }

  Future<void> _toggleDarkMode(bool value) async {
    final settings = await SettingsService.getInstance();
    await settings.setDarkMode(value);
    setState(() => _isDarkMode = value);
  }

  Future<void> _toggleNotifications(bool value) async {
    final settings = await SettingsService.getInstance();
    await settings.setNotificationsEnabled(value);
    setState(() => _notificationsEnabled = value);
  }

  Future<void> _backupData() async {
    try {
      final dir = await getApplicationDocumentsDirectory();
      final file = File(
        '${dir.path}/backup_${DateTime.now().toIso8601String()}.json',
      );
      await DatabaseService().exportData(file);

      await Share.shareFiles([file.path], text: '宝宝健康追踪器数据备份');
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('备份失败: $e')));
    }
  }

  Future<void> _restoreData() async {
    // Implement file picker and data restore logic
  }

  Future<void> _clearData() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text('清除确认'),
            content: Text('确定要删除所有数据吗？此操作不可恢复。'),
            actions: [
              TextButton(
                child: Text('取消'),
                onPressed: () => Navigator.pop(context, false),
              ),
              TextButton(
                child: Text('清除'),
                style: TextButton.styleFrom(foregroundColor: Colors.red),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          ),
    );

    if (confirmed == true) {
      await DatabaseService().clearAllData();
      _loadBabies();
    }
  }

  void _showPrivacyPolicy() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text('隐私政策'),
            content: SingleChildScrollView(
              child: Text(
                '本应用不会收集或上传任何个人信息。所有数据均存储在本地。'
                '\n\n您可以随时备份或删除您的数据。',
              ),
            ),
            actions: [
              TextButton(
                child: Text('确定'),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
    );
  }

  Future<void> _showColorPicker() async {
    // Implement color picker dialog
    // You can use flutter_colorpicker package
  }

  Future<void> _toggleBackupReminder(bool value) async {
    final settings = await SettingsService.getInstance();
    await settings.setBackupReminderEnabled(value);
    setState(() => _backupReminderEnabled = value);
  }

  Future<void> _changeLanguage(String? value) async {
    if (value != null) {
      final settings = await SettingsService.getInstance();
      await settings.setLanguage(value);
      setState(() => _language = value);
      // Implement language change logic
    }
  }

  Future<void> _resetSettings() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: Text('重置确认'),
            content: Text('确定要恢复默认设置吗？'),
            actions: [
              TextButton(
                child: Text('取消'),
                onPressed: () => Navigator.pop(context, false),
              ),
              TextButton(
                child: Text('重置'),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          ),
    );

    if (confirmed == true) {
      final settings = await SettingsService.getInstance();
      await settings.resetToDefaults();
      await _loadSettings();
    }
  }

  void _showThemeSelector() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('选择主题'),
            content: SizedBox(
              width: double.maxFinite,
              child: ListenableBuilder(
                listenable: ThemeNotifier.instance,
                builder: (context, child) {
                  return ListView.builder(
                    shrinkWrap: true,
                    itemCount: ThemeService.themes.length,
                    itemBuilder: (context, index) {
                      final themeName = ThemeService.themes.keys.elementAt(
                        index,
                      );
                      final theme = ThemeService.themes[themeName]!;

                      return RadioListTile<String>(
                        title: Text(themeName),
                        value: themeName,
                        groupValue: ThemeNotifier.instance.currentTheme,
                        secondary: Container(
                          width: 24,
                          height: 24,
                          decoration: BoxDecoration(
                            color: theme.colorScheme.primary,
                            shape: BoxShape.circle,
                          ),
                        ),
                        onChanged: (value) async {
                          if (value != null) {
                            await ThemeNotifier.instance.setTheme(value);
                            Navigator.pop(context);
                          }
                        },
                      );
                    },
                  );
                },
              ),
            ),
          ),
    );
  }
}
